'use strict';

const uniIdCommon = require('uni-id-common');
const db = uniCloud.database();
const dbCmd = db.command;

/**
 * 记录积分变化（内联版本）
 * 注意：此函数应该在积分已经更新之后调用
 * balance_after 会自动查询当前最新的积分余额
 */
async function logPointChange({ userId, changeAmount, changeType, description, relatedOrderId = null }) {
  try {
    // 查询用户当前积分（此时积分已经更新过了）
    const userRes = await db.collection('users').doc(userId).field({ points: 1 }).get();
    if (!userRes.data || userRes.data.length === 0) {
      console.error(`[积分记录] 用户不存在: ${userId}`);
      return;
    }
    const currentPoints = userRes.data[0].points || 0;
    // balance_after 就是当前积分（因为积分已经更新过了）
    const balanceAfter = currentPoints;

    await db.collection('point_records').add({
      user_id: userId,
      change_amount: changeAmount,
      change_type: changeType,
      description: description,
      related_order_id: relatedOrderId,
      balance_after: balanceAfter,
      create_time: Date.now()
    });
    console.log(`[积分记录] 用户 ${userId} 积分变化: ${changeAmount > 0 ? '+' : ''}${changeAmount}, 余额: ${balanceAfter}, 原因: ${description}`);
  } catch (error) {
    console.error(`[积分记录] 记录失败:`, error);
  }
}

/**
 * 检查用户等级升级（内联版本）
 */
async function checkLevelUp(userId) {
  if (!userId) return;
  try {
    const userRes = await db.collection('users').doc(userId).field({ 'points': 1, 'level': 1 }).get();
    if (!userRes.data || userRes.data.length === 0) {
      console.error(`[checkLevelUp] User not found: ${userId}`);
      return;
    }
    const user = userRes.data[0];
    const userPoints = user.points || 0;
    const currentLevel = user.level;

    const levels = [
      { "name": "健康分享者", "points_required": 0, "commission_rate": 0.10 },
      { "name": "推广大使", "points_required": 100, "commission_rate": 0.15 },
      { "name": "区域代理", "points_required": 500, "commission_rate": 0.20 }
    ];
    const sortedLevels = [...levels].sort((a, b) => b.points_required - a.points_required);

    let newLevel = '健康分享者';
    for (const level of sortedLevels) {
      if (userPoints >= level.points_required) {
        newLevel = level.name;
        break;
      }
    }

    if (newLevel !== currentLevel) {
      await db.collection('users').doc(userId).update({ level: newLevel });
      console.log(`用户 ${userId} 已成功升级到 ${newLevel}`);
    }
  } catch (e) {
    console.error(`[checkLevelUp] Error for user ${userId}:`, e);
  }
}

/**
 * 获取用户等级对应的佣金比例
 * @param {string} userId - 用户ID
 * @param {object} commissionRules - 佣金规则配置
 * @returns {number} 佣金比例 (0-1之间)
 */
async function getCommissionRateByUserLevel(userId, commissionRules) {
  try {
    // 获取用户信息（积分和等级）
    const userRes = await db.collection('users').doc(userId).field({
      points: true,
      level: true
    }).get();

    if (!userRes.data || userRes.data.length === 0) {
      console.log(`[佣金计算] 用户 ${userId} 不存在，使用默认比例`);
      return commissionRules?.default_rate || 0.1;
    }

    const user = userRes.data[0];
    const userPoints = user.points || 0;

    // 获取分级佣金配置
    const levels = commissionRules?.levels || [];
    if (!Array.isArray(levels) || levels.length === 0) {
      console.log(`[佣金计算] 未找到分级佣金配置，使用默认比例`);
      return commissionRules?.default_rate || 0.1;
    }

    // 根据用户积分找到对应的等级
    let userLevelRate = commissionRules?.default_rate || 0.1;

    // 按积分要求从高到低排序，找到第一个满足条件的等级
    const sortedLevels = [...levels].sort((a, b) => b.points_required - a.points_required);

    for (const level of sortedLevels) {
      if (userPoints >= level.points_required) {
        userLevelRate = level.commission_rate;
        console.log(`[佣金计算] 用户 ${userId} 积分 ${userPoints}，匹配等级 ${level.name}，佣金比例 ${level.commission_rate}`);
        break;
      }
    }

    console.log(`[佣金计算] 用户 ${userId} 最终佣金比例: ${userLevelRate}`);
    return userLevelRate;

  } catch (error) {
    console.error(`[佣金计算] 获取用户佣金比例失败:`, error);
    return commissionRules?.default_rate || 0.1;
  }
}

/**
 * 处理订单状态变化的业务逻辑
 * @param {string} orderId - 订单ID
 * @param {string} oldStatus - 旧状态
 * @param {string} newStatus - 新状态
 * @param {object} existingOrder - 已存在的订单数据
 * @param {string} promoterId - 推荐人ID
 * @param {string} buyerUid - 购买者ID
 * @param {object} rules - 分销规则
 * @param {function} addLog - 日志函数
 */
async function handleOrderStatusChange(orderId, oldStatus, newStatus, existingOrder, promoterId, buyerUid, rules, addLog) {
  addLog(`[DEBUG] 处理订单状态变化: ${oldStatus} → ${newStatus}`);

  // 1. 待付款 → 已取消：无需处理（还没发放佣金）
  if (oldStatus === 'unpaid' && newStatus === 'cancelled') {
    addLog(`[INFO] 订单 ${orderId} 从待付款变为已取消，无需处理`);
    return;
  }

  // 2. 待发货/待收货 → 已取消：需要核减待激活佣金
  if ((oldStatus === 'paid' || oldStatus === 'shipped') && newStatus === 'cancelled') {
    if (promoterId && existingOrder.commission_amount > 0 && existingOrder.commission_status === 'pending') {
      try {
        await db.collection('users').doc(promoterId).update({
          commission_pending: dbCmd.inc(-existingOrder.commission_amount)
        });
        await db.collection('orders').doc(orderId).update({
          commission_status: 'cancelled'
        });
        addLog(`[INFO] ✅ 订单取消，已核减推荐人 ${promoterId} 的待激活佣金 ${existingOrder.commission_amount} 分`);
      } catch (err) {
        addLog(`[ERROR] 核减佣金失败: ${err.message}`);
      }
    }
    return;
  }

  // 3. 待付款 → 待发货：发放待激活佣金
  if (oldStatus === 'unpaid' && newStatus === 'paid') {
    if (promoterId && existingOrder.commission_amount > 0) {
      try {
        await db.collection('users').doc(promoterId).update({
          commission_pending: dbCmd.inc(existingOrder.commission_amount)
        });
        await db.collection('orders').doc(orderId).update({
          commission_status: 'pending'
        });
        addLog(`[INFO] ✅ 订单已支付，为推荐人 ${promoterId} 增加待激活佣金 ${existingOrder.commission_amount} 分`);
      } catch (err) {
        addLog(`[ERROR] 增加佣金失败: ${err.message}`);
      }
    }
    return;
  }

  // 4. 任意状态 → 已完成：发放积分和佣金，设置激活倒计时
  if (newStatus === 'completed' && oldStatus !== 'completed') {
    addLog(`[INFO] 订单完成，开始发放积分和佣金...`);

    try {
      // ✅ 修复：如果订单从 'paid' 或 'shipped' 变为 'completed'，需要增加待激活佣金
      // 检查佣金是否已经增加过（commission_status 为 'pending' 表示已增加）
      if (promoterId && existingOrder.commission_amount > 0 && !existingOrder.commission_status) {
        // 佣金还没有增加过，现在增加
        await db.collection('users').doc(promoterId).update({
          commission_pending: dbCmd.inc(existingOrder.commission_amount)
        });
        addLog(`[INFO] ✅ 订单完成，为推荐人 ${promoterId} 增加待激活佣金 ${existingOrder.commission_amount} 分`);
      }

      // 为购买用户增加积分（如果还没发放）
      if (!existingOrder.buyer_points_awarded || existingOrder.buyer_points_awarded === 0) {
        const buyerPoints = rules.points?.purchaseComplete || 10;
        await db.collection('users').doc(buyerUid).update({
          points: dbCmd.inc(buyerPoints)
        });
        addLog(`[INFO] ✅ 为购买用户 ${buyerUid} 增加 ${buyerPoints} 积分`);

        // 记录积分变化
        await logPointChange({
          userId: buyerUid,
          changeAmount: buyerPoints,
          changeType: 'purchase_complete',
          description: `购买订单完成`,
          relatedOrderId: orderId
        });

        // 更新订单记录
        await db.collection('orders').doc(orderId).update({
          buyer_points_awarded: buyerPoints
        });
      }

      // 为推广人增加积分（如果有推荐人且还没发放）
      if (promoterId && (!existingOrder.points_awarded || existingOrder.points_awarded === 0)) {
        const promoterPoints = rules.points?.purchaseComplete || 10;
        await db.collection('users').doc(promoterId).update({
          points: dbCmd.inc(promoterPoints)
        });
        addLog(`[INFO] ✅ 为推荐人 ${promoterId} 增加 ${promoterPoints} 积分`);

        // 记录积分变化
        await logPointChange({
          userId: promoterId,
          changeAmount: promoterPoints,
          changeType: 'promotion_complete',
          description: `推广订单完成`,
          relatedOrderId: orderId
        });

        // 更新订单记录
        await db.collection('orders').doc(orderId).update({
          points_awarded: promoterPoints
        });
      }
    } catch (err) {
      addLog(`[ERROR] 发放积分或佣金失败: ${err.message}`);
    }
    return;
  }

  // 5. 已完成 → 已取消/已退款：需要核减积分和佣金
  if (oldStatus === 'completed' && (newStatus === 'cancelled' || newStatus === 'refunded')) {
    addLog(`[WARN] 订单从已完成变为${newStatus}，需要核减积分和佣金`);

    try {
      // 核减购买用户积分
      if (existingOrder.buyer_points_awarded > 0) {
        await db.collection('users').doc(buyerUid).update({
          points: dbCmd.inc(-existingOrder.buyer_points_awarded)
        });
        addLog(`[INFO] ✅ 已核减购买用户 ${buyerUid} 的积分 ${existingOrder.buyer_points_awarded}`);

        // 记录积分变化
        await logPointChange({
          userId: buyerUid,
          changeAmount: -existingOrder.buyer_points_awarded,
          changeType: newStatus === 'cancelled' ? 'order_cancel' : 'order_refund',
          description: `订单${newStatus === 'cancelled' ? '取消' : '退款'}核减`,
          relatedOrderId: orderId
        });
      }

      // 核减推广人积分
      if (promoterId && existingOrder.points_awarded > 0) {
        await db.collection('users').doc(promoterId).update({
          points: dbCmd.inc(-existingOrder.points_awarded)
        });
        addLog(`[INFO] ✅ 已核减推荐人 ${promoterId} 的积分 ${existingOrder.points_awarded}`);

        // 记录积分变化
        await logPointChange({
          userId: promoterId,
          changeAmount: -existingOrder.points_awarded,
          changeType: newStatus === 'cancelled' ? 'order_cancel' : 'order_refund',
          description: `推广订单${newStatus === 'cancelled' ? '取消' : '退款'}核减`,
          relatedOrderId: orderId
        });
      }

      // 核减佣金（根据佣金状态）
      if (promoterId && existingOrder.commission_amount > 0) {
        if (existingOrder.commission_status === 'pending') {
          // 待激活佣金
          await db.collection('users').doc(promoterId).update({
            commission_pending: dbCmd.inc(-existingOrder.commission_amount)
          });
          addLog(`[INFO] ✅ 已核减推荐人 ${promoterId} 的待激活佣金 ${existingOrder.commission_amount} 分`);
        } else if (existingOrder.commission_status === 'activated') {
          // 已激活佣金（可提现余额）
          await db.collection('users').doc(promoterId).update({
            commission_available: dbCmd.inc(-existingOrder.commission_amount),
            commission_total: dbCmd.inc(-existingOrder.commission_amount)
          });
          addLog(`[INFO] ✅ 已核减推荐人 ${promoterId} 的可提现佣金 ${existingOrder.commission_amount} 分`);
        }

        // 更新订单佣金状态
        await db.collection('orders').doc(orderId).update({
          commission_status: 'cancelled'
        });
      }
    } catch (err) {
      addLog(`[ERROR] 核减积分和佣金失败: ${err.message}`);
    }
    return;
  }

  // 6. ✅ 新增：任意其他状态 → 已取消/已退款：统一处理佣金状态
  // 处理所有未被上述场景覆盖的状态变化（如 unpaid→refunded, paid→refunded, shipped→refunded 等）
  if ((newStatus === 'cancelled' || newStatus === 'refunded') && oldStatus !== 'completed') {
    addLog(`[WARN] 订单从${oldStatus}变为${newStatus}，需要处理佣金状态`);

    try {
      // 如果有待激活佣金，需要核减
      if (promoterId && existingOrder.commission_amount > 0 && existingOrder.commission_status === 'pending') {
        await db.collection('users').doc(promoterId).update({
          commission_pending: dbCmd.inc(-existingOrder.commission_amount)
        });
        addLog(`[INFO] ✅ 已核减推荐人 ${promoterId} 的待激活佣金 ${existingOrder.commission_amount} 分`);
      }

      // 更新订单佣金状态为 'cancelled'（无论之前是什么状态）
      if (promoterId && existingOrder.commission_amount > 0) {
        await db.collection('orders').doc(orderId).update({
          commission_status: 'cancelled'
        });
        addLog(`[INFO] ✅ 订单佣金状态已更新为 'cancelled'`);
      }
    } catch (err) {
      addLog(`[ERROR] 处理订单取消/退款失败: ${err.message}`);
    }
    return;
  }

  addLog(`[DEBUG] 状态变化 ${oldStatus} → ${newStatus} 无需特殊处理`);
}

exports.main = async (event, context) => {
  const { action, params } = event;
  let result = {};

  const uniIdIns = uniIdCommon.createInstance({ context });

  // syncWechatOrders and testWechatAPI actions do not require token check
  const noAuthActions = ['syncWechatOrders', 'testWechatAPI'];
  if (!noAuthActions.includes(action)) {
      const payload = await uniIdIns.checkToken(event.uniIdToken);
      if (payload.errCode) {
        return payload;
      }
      // Attach uid to event for easier access in other actions
      event.uid = payload.uid;
  }

  switch (action) {
    case 'syncWechatOrders': {
      const debugLogs = []; // 收集所有日志
      const addLog = (msg) => {
        console.log(msg);
        debugLogs.push(msg);
      };

      try {
        addLog('[DEBUG] ===== 步骤1：获取access_token =====');
        const tokenRes = await uniCloud.callFunction({
          name: 'wx-api-center',
          data: { action: 'getAccessToken' }
        });
        addLog('[DEBUG] wx-api-center响应: ' + JSON.stringify(tokenRes.result));

        if (tokenRes.result.code !== 0) {
          throw new Error(tokenRes.result.message);
        }
        const accessToken = tokenRes.result.accessToken;
        addLog('[DEBUG] access_token获取成功: ' + (accessToken ? '有值' : '无值'));

        // 查询最近7天的订单（增量更新）
        addLog('[DEBUG] ===== 步骤2：查询微信小店订单 =====');
        addLog('[DEBUG] 查询最近7天的订单');

        // 计算时间范围：最近7天
        const now = new Date();
        const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);

        const startTime = sevenDaysAgo;
        const endTime = now;

        addLog('[DEBUG] 查询时间范围: ' + JSON.stringify({
          start: startTime.toISOString(),
          end: endTime.toISOString(),
          start_timestamp: Math.floor(startTime.getTime() / 1000),
          end_timestamp: Math.floor(endTime.getTime() / 1000),
          days: 7
        }));

        const listUrl = `https://api.weixin.qq.com/channels/ec/order/list/get?access_token=${accessToken}`;

        const requestData = {
          create_time_range: {
            start_time: Math.floor(startTime.getTime() / 1000),
            end_time: Math.floor(endTime.getTime() / 1000)
          },
          page_size: 100
        };

        addLog('[DEBUG] 请求URL: ' + listUrl.substring(0, 100) + '...');
        addLog('[DEBUG] 请求参数: ' + JSON.stringify(requestData));

        const listRes = await uniCloud.httpclient.request(listUrl, {
          method: 'POST',
          contentType: 'json',
          dataType: 'json',
          data: requestData
        });

        addLog('[DEBUG] ===== 步骤3：微信API响应分析 =====');
        addLog('[DEBUG] HTTP状态码: ' + listRes.status);
        addLog('[DEBUG] 响应数据: ' + JSON.stringify(listRes.data));

        if (!listRes.data) {
          addLog('[ERROR] API返回数据为空');
          return {
            code: 500,
            message: '微信API返回数据为空，请检查access_token是否有效',
            debugLogs: debugLogs
          };
        }

        addLog('[DEBUG] errcode: ' + listRes.data.errcode);
        addLog('[DEBUG] errmsg: ' + listRes.data.errmsg);

        if (listRes.data.errcode !== 0) {
          addLog('[ERROR] 微信API返回错误');
          return {
            code: 500,
            message: `微信API错误: [${listRes.data.errcode}] ${listRes.data.errmsg}`,
            debugLogs: debugLogs
          };
        }

        const orderIdList = listRes.data.order_id_list || [];
        addLog('[DEBUG] ===== 步骤4：订单ID列表 =====');
        addLog('[DEBUG] order_id_list: ' + JSON.stringify(orderIdList));
        addLog('[DEBUG] 订单数量: ' + orderIdList.length);

        if (orderIdList.length === 0) {
          addLog('[WARN] 最近7天没有订单');
          return {
            code: 0,
            message: '最近7天没有订单（微信API返回空列表）',
            syncedCount: 0,
            debugLogs: debugLogs
          };
        }

        addLog('[DEBUG] ===== 步骤5：开始处理订单详情 =====');

        addLog('[DEBUG] ===== 步骤6：逐个处理订单详情 =====');
        let syncedCount = 0;
        let skippedCount = 0;
        let errorCount = 0;

        // 添加超时保护：最多处理30秒
        const processingStartTime = Date.now();
        const MAX_EXECUTION_TIME = 30000; // 30秒
        const REQUEST_TIMEOUT = 5000; // 单个请求5秒超时
        const BATCH_SIZE = 10; // 每批处理10个订单

        for (let i = 0; i < orderIdList.length; i++) {
          // 检查总体执行时间
          if (Date.now() - processingStartTime > MAX_EXECUTION_TIME) {
            addLog(`[WARN] 执行时间超过 ${MAX_EXECUTION_TIME}ms，停止处理剩余订单`);
            addLog(`[WARN] 已处理: ${i}/${orderIdList.length} 订单`);
            break;
          }

          const orderId = orderIdList[i];
          addLog(`[DEBUG] ===== 处理订单 ${i + 1}/${orderIdList.length}: ${orderId} =====`);

          // 检查订单是否已存在
          const existCheck = await db.collection('orders').doc(orderId).get();
          const existingOrder = existCheck.data.length > 0 ? existCheck.data[0] : null;
          addLog(`[DEBUG] 订单是否已存在: ${existingOrder ? '是' : '否'}`);

          if (existingOrder) {
            addLog(`[DEBUG] 订单 ${orderId} 已存在，当前状态: ${existingOrder.status}`);
          }

          // 获取订单详情
          addLog(`[DEBUG] 开始获取订单 ${orderId} 的详情...`);
          const detailUrl = `https://api.weixin.qq.com/channels/ec/order/get?access_token=${accessToken}`;

          let detailRes;
          try {
            // 添加超时控制
            const timeoutPromise = new Promise((_, reject) =>
              setTimeout(() => reject(new Error(`请求超时（${REQUEST_TIMEOUT}ms）`)), REQUEST_TIMEOUT)
            );

            const requestPromise = uniCloud.httpclient.request(detailUrl, {
              method: 'POST',
              contentType: 'json',
              dataType: 'json',
              data: { order_id: orderId },
              timeout: REQUEST_TIMEOUT
            });

            detailRes = await Promise.race([requestPromise, timeoutPromise]);
            console.log(`[DEBUG] 订单详情API响应:`, JSON.stringify(detailRes.data, null, 2));
          } catch (err) {
            console.error(`[ERROR] 获取订单 ${orderId} 详情时网络错误:`, err.message);
            errorCount++;
            continue;
          }

          if (!detailRes.data) {
            console.error(`[ERROR] 订单 ${orderId} 详情API返回数据为空`);
            errorCount++;
            continue;
          }

          if (detailRes.data.errcode !== 0) {
            console.error(`[ERROR] 订单 ${orderId} 详情API返回错误: [${detailRes.data.errcode}] ${detailRes.data.errmsg}`);
            errorCount++;
            continue;
          }

          const { order } = detailRes.data;
          if (!order) {
            addLog(`[ERROR] 订单 ${orderId} 详情中没有order字段`);
            errorCount++;
            continue;
          }

          addLog(`[DEBUG] 订单 ${orderId} 基本信息: ${JSON.stringify({
            order_id: order.order_id,
            openid: order.openid,
            unionid: order.unionid,
            create_time: order.create_time,
            status: order.status
          })}`);

          const openid = order.openid;
          const unionid = order.unionid;

          if (!openid && !unionid) {
            addLog(`[ERROR] 订单 ${orderId} 没有openid和unionid字段`);
            errorCount++;
            continue;
          }

          addLog(`[DEBUG] 订单openid: ${openid}, unionid: ${unionid || '无'}`);

          addLog(`[DEBUG] 开始查询用户...`);

          let userQuery = { data: [] };
          const wechatStoreAppId = 'wx64874b77c972fb53';

          // 优先使用 UnionID 查询（最可靠）
          if (unionid) {
            addLog(`[DEBUG] 使用UnionID查询: ${unionid}`);
            userQuery = await db.collection('users').where({ wx_unionid: unionid }).limit(1).get();
            addLog(`[DEBUG] UnionID查询结果数量: ${userQuery.data.length}`);

            if (userQuery.data.length > 0) {
              const user = userQuery.data[0];
              addLog(`[DEBUG] 通过UnionID找到用户: ${user._id}`);
              addLog(`[DEBUG] 用户当前wx_openid: ${JSON.stringify(user.wx_openid)}`);

              // 更新用户的微信小店 openid（如果还没有）
              let needUpdate = false;
              let newWxOpenid = {};

              // 检查 wx_openid 的类型
              if (typeof user.wx_openid === 'string') {
                // 如果是字符串，转换为对象
                addLog(`[DEBUG] wx_openid是字符串，需要转换为对象`);
                newWxOpenid = {};
                newWxOpenid[wechatStoreAppId] = openid;
                needUpdate = true;
              } else if (typeof user.wx_openid === 'object' && user.wx_openid !== null) {
                // 如果是对象，检查是否有小店的openid
                if (!user.wx_openid[wechatStoreAppId]) {
                  addLog(`[DEBUG] wx_openid对象中没有小店openid，需要添加`);
                  newWxOpenid = { ...user.wx_openid };
                  newWxOpenid[wechatStoreAppId] = openid;
                  needUpdate = true;
                }
              } else {
                // 如果不存在，创建新对象
                addLog(`[DEBUG] wx_openid不存在，需要创建`);
                newWxOpenid = {};
                newWxOpenid[wechatStoreAppId] = openid;
                needUpdate = true;
              }

              if (needUpdate) {
                addLog(`[DEBUG] 更新wx_openid为: ${JSON.stringify(newWxOpenid)}`);
                try {
                  // 使用 dbCmd.set() 强制替换字段值
                  await db.collection('users').doc(user._id).update({
                    wx_openid: dbCmd.set(newWxOpenid)
                  });
                  addLog(`[DEBUG] 已更新wx_openid`);
                } catch (updateError) {
                  addLog(`[ERROR] 更新wx_openid失败: ${updateError.message}`);
                  addLog(`[ERROR] 请手动在数据库中将用户 ${user._id} 的 wx_openid 改为对象格式`);
                  addLog(`[ERROR] 手动修改步骤：`);
                  addLog(`[ERROR] 1. 打开 uniCloud Web 控制台`);
                  addLog(`[ERROR] 2. 进入云数据库 → users 表`);
                  addLog(`[ERROR] 3. 找到用户 ${user._id}`);
                  addLog(`[ERROR] 4. 将 wx_openid 从字符串改为: ${JSON.stringify(newWxOpenid)}`);
                  throw updateError;
                }
              } else {
                addLog(`[DEBUG] wx_openid已包含小店openid，无需更新`);
              }
            }
          }

          // 如果没有 UnionID 或通过 UnionID 没找到，尝试用 openid 查询
          if (userQuery.data.length === 0 && openid) {
            addLog(`[DEBUG] UnionID未找到或为空，尝试使用OpenID查询: ${openid}`);
            const queryCondition = {};
            queryCondition[`wx_openid.${wechatStoreAppId}`] = openid;

            userQuery = await db.collection('users').where(queryCondition).limit(1).get();
            addLog(`[DEBUG] OpenID查询结果数量: ${userQuery.data.length}`);

            if (userQuery.data.length > 0 && unionid) {
              // 如果通过 openid 找到了用户，且订单有 unionid，则更新用户的 unionid
              const user = userQuery.data[0];
              if (!user.wx_unionid) {
                addLog(`[DEBUG] 为用户添加UnionID: ${unionid}`);
                await db.collection('users').doc(user._id).update({ wx_unionid: unionid });
                addLog(`[DEBUG] 已添加UnionID`);
              }
            }
          }

          // 如果还是没找到，且是旧订单（没有unionid），尝试手动匹配
          if (userQuery.data.length === 0 && !unionid && openid) {
            addLog(`[DEBUG] 旧订单（无UnionID），尝试手动匹配当前登录用户...`);
            addLog(`[DEBUG] 订单OpenID: ${openid}`);
            addLog(`[DEBUG] 提示：这是一个旧订单，需要手动关联。请在小店下新订单以自动关联。`);

            // 对于旧订单，我们暂时跳过，等待用户下新订单
            // 或者可以提供一个手动关联的功能
          }

          if (userQuery.data.length > 0) {
            addLog(`[DEBUG] 找到用户: ${JSON.stringify({
              _id: userQuery.data[0]._id,
              wx_unionid: userQuery.data[0].wx_unionid,
              wx_openid: userQuery.data[0].wx_openid,
              promoter_id: userQuery.data[0].promoter_id
            })}`);
          }

          if (userQuery.data.length === 0) {
            addLog(`[WARN] 订单 ${orderId} 的购买用户未在系统中找到`);
            addLog(`[WARN] UnionID: ${unionid || '无（旧订单）'}, OpenID: ${openid}`);
            if (!unionid) {
              addLog(`[WARN] 这是一个旧订单（绑定开放平台之前），无法自动匹配`);
              addLog(`[WARN] 建议：在微信小店下一个新订单，新订单会包含UnionID，可以自动匹配`);
            } else {
              addLog(`[WARN] 提示：请确保该用户已经登录过小程序`);
            }
            skippedCount++;
            continue;
          }
          // 获取用户信息
          const buyerInfo = userQuery.data[0];
          const buyerUid = buyerInfo._id;
          const promoterId = buyerInfo.promoter_id;
          addLog(`[DEBUG] 买家UID: ${buyerUid}, 推荐人ID: ${promoterId || '无'}`);

          // 获取分销规则
          console.log(`[DEBUG] 开始获取分销规则...`);
          const settingsRes = await db.collection('settings').doc('rules').get();
          console.log(`[DEBUG] 分销规则查询结果:`, settingsRes.data.length);
          const rules = settingsRes.data.length > 0 ? settingsRes.data[0] : {};
          console.log(`[DEBUG] 分销规则:`, JSON.stringify(rules, null, 2));

          // 映射微信订单状态到我们的状态
          // 参考: https://developers.weixin.qq.com/doc/store/shop/API/channels-shop-order/api_getorder.html
          const wechatStatus = order.status;
          let ourStatus = 'paid'; // 默认状态
          let completedTime = null;

          // 微信订单状态映射
          // 10: 待付款, 20: 待发货, 30: 待收货, 100: 完成, 200: 全部取消, 250: 全部售后
          if (wechatStatus === 100) {
            ourStatus = 'completed';
            completedTime = Date.now();
          } else if (wechatStatus === 200) {
            ourStatus = 'cancelled';
          } else if (wechatStatus === 250) {
            ourStatus = 'refunded';
          } else if (wechatStatus === 30) {
            ourStatus = 'shipped'; // 待收货
          } else if (wechatStatus === 20) {
            ourStatus = 'paid'; // 待发货
          } else if (wechatStatus === 10) {
            ourStatus = 'unpaid'; // 待付款
          }

          addLog(`[DEBUG] 微信订单状态: ${wechatStatus}, 映射为: ${ourStatus}`);

          // 如果订单已存在，检查状态是否变化
          if (existingOrder) {
            if (existingOrder.status === ourStatus) {
              addLog(`[DEBUG] 订单 ${orderId} 状态未变化，跳过`);
              skippedCount++;
              continue;
            }
            addLog(`[INFO] 订单 ${orderId} 状态变化: ${existingOrder.status} → ${ourStatus}`);
          }

          // 计算佣金金额（按用户等级的百分比）
          const orderAmount = order.order_detail.price_info.order_price;
          let commissionRate = 0.1; // 默认10%

          // 如果有推荐人，根据推荐人等级计算佣金比例
          if (promoterId) {
            try {
              commissionRate = await getCommissionRateByUserLevel(promoterId, rules.commission_rules);
            } catch (error) {
              console.error(`[订单同步] 获取推荐人佣金比例失败，使用默认值:`, error);
              commissionRate = rules.commission_rules?.default_rate || 0.1;
            }
          }

          const commissionAmount = promoterId ? Math.round(orderAmount * commissionRate) : 0;

          addLog(`[DEBUG] 订单金额: ${orderAmount}分, 佣金比例: ${commissionRate * 100}%, 佣金金额: ${commissionAmount}分`);

          // 如果订单不存在，创建新订单
          if (!existingOrder) {
            addLog(`[DEBUG] 创建新订单 ${orderId}...`);

            // 构建订单数据
            const orderData = {
              _id: order.order_id,
              buyer_id: buyerUid,
              promoter_id: promoterId || null,
              amount: orderAmount,
              status: ourStatus,
              create_time: order.create_time * 1000,
              completed_time: completedTime,
              product_details: order.order_detail.product_infos.map(p => ({
                name: p.title,
                quantity: p.count,
                price: p.sale_price
              })),
              commission_amount: commissionAmount,
              // ✅ 修复：根据订单状态设置佣金状态
              // 如果订单创建时就是取消或退款状态，直接设置为 'cancelled'，不发放佣金
              // 否则设置为 'pending'
              commission_status: (() => {
                if (!promoterId || commissionAmount <= 0) return null;
                if (ourStatus === 'cancelled' || ourStatus === 'refunded') return 'cancelled';
                return 'pending';
              })(),
              points_awarded: 0,
              buyer_points_awarded: 0,
              source: 'wechat_store',
              last_sync_time: Date.now(),
              activation_countdown: 7,
              activation_date: null
            };

            // 如果订单已完成，设置完成时间和激活日期
            if (ourStatus === 'completed' && completedTime) {
              orderData.completed_time = completedTime;
              orderData.activation_date = completedTime + 7 * 24 * 60 * 60 * 1000; // 7天后
              orderData.activation_countdown = 7;
            }

            // 插入订单
            try {
              await db.collection('orders').add(orderData);
              addLog(`[DEBUG] ✅ 订单 ${orderId} 创建成功`);
            } catch (dbErr) {
              addLog(`[ERROR] 订单 ${orderId} 创建失败: ${dbErr.message}`);
              errorCount++;
              continue;
            }

            // 只有订单状态为"待发货"(paid)或更高状态时，才增加待激活佣金
            // ✅ 修复：如果订单是取消或退款状态，不发放佣金
            if (promoterId && (ourStatus === 'paid' || ourStatus === 'shipped' || ourStatus === 'completed')) {
              try {
                await db.collection('users').doc(promoterId).update({
                  commission_pending: dbCmd.inc(commissionAmount)
                });
                addLog(`[DEBUG] ✅ 为推荐人 ${promoterId} 增加待激活佣金 ${commissionAmount} 分（订单状态: ${ourStatus}）`);
              } catch (updateErr) {
                addLog(`[ERROR] 更新推荐人佣金失败: ${updateErr.message}`);
              }
            } else if (promoterId && (ourStatus === 'cancelled' || ourStatus === 'refunded')) {
              addLog(`[INFO] 订单 ${orderId} 状态为 ${ourStatus}，不发放佣金（订单已取消/退款）`);
            } else if (promoterId) {
              addLog(`[INFO] 订单 ${orderId} 状态为 ${ourStatus}，暂不发放佣金`);
            } else {
              addLog(`[INFO] 订单 ${orderId} 没有推荐人，不产生佣金`);
            }

            // 订单完成时发放积分（新逻辑：等到订单完成才发放）
            if (ourStatus === 'completed') {
              try {
                // 为购买用户增加积分
                const buyerPoints = rules.points?.purchaseComplete || 10;
                await db.collection('users').doc(buyerUid).update({
                  points: dbCmd.inc(buyerPoints)
                });
                addLog(`[DEBUG] ✅ 为购买用户 ${buyerUid} 增加 ${buyerPoints} 积分（订单已完成）`);

                // 记录积分变化
                await logPointChange({
                  userId: buyerUid,
                  changeAmount: buyerPoints,
                  changeType: 'purchase_complete',
                  description: `购买订单完成`,
                  relatedOrderId: orderId
                });

                // 为推广人增加积分（如果有推荐人）
                if (promoterId) {
                  const promoterPoints = rules.points?.purchaseComplete || 10;
                  await db.collection('users').doc(promoterId).update({
                    points: dbCmd.inc(promoterPoints)
                  });
                  addLog(`[DEBUG] ✅ 为推荐人 ${promoterId} 增加 ${promoterPoints} 积分（推广订单已完成）`);

                  // 记录积分变化
                  await logPointChange({
                    userId: promoterId,
                    changeAmount: promoterPoints,
                    changeType: 'promotion_complete',
                    description: `推广订单完成`,
                    relatedOrderId: orderId
                  });

                  // 更新订单的积分奖励记录
                  await db.collection('orders').doc(orderId).update({
                    points_awarded: promoterPoints,
                    buyer_points_awarded: buyerPoints
                  });
                }
              } catch (pointsErr) {
                addLog(`[ERROR] 发放积分失败: ${pointsErr.message}`);
              }
            }

            syncedCount++;
            addLog(`[DEBUG] 订单 ${orderId} 创建完成`);
          } else {
            // 订单已存在，更新状态
            addLog(`[DEBUG] 更新订单 ${orderId} 状态...`);

            const oldStatus = existingOrder.status;
            const updateData = {
              status: ourStatus,
              last_sync_time: Date.now()
            };

            // 如果订单变为已完成，设置完成时间和激活日期
            if (ourStatus === 'completed' && !existingOrder.completed_time) {
              updateData.completed_time = Date.now();
              updateData.activation_date = Date.now() + 7 * 24 * 60 * 60 * 1000; // 7天后
              updateData.activation_countdown = 7;
              // ✅ 修复：订单完成时，如果有推荐人和佣金，设置佣金状态为 'pending'
              if (promoterId && existingOrder.commission_amount > 0 && !existingOrder.commission_status) {
                updateData.commission_status = 'pending';
                addLog(`[DEBUG] 订单完成，设置佣金状态为 'pending'`);
              }
              addLog(`[DEBUG] 订单完成，设置激活日期为7天后`);
            }

            try {
              await db.collection('orders').doc(orderId).update(updateData);
              addLog(`[DEBUG] ✅ 订单 ${orderId} 状态更新成功: ${oldStatus} → ${ourStatus}`);
            } catch (updateErr) {
              addLog(`[ERROR] 更新订单状态失败: ${updateErr.message}`);
              errorCount++;
              continue;
            }

            // 处理状态变化的业务逻辑
            await handleOrderStatusChange(orderId, oldStatus, ourStatus, existingOrder, promoterId, buyerUid, rules, addLog);

            syncedCount++;
            addLog(`[DEBUG] 订单 ${orderId} 更新完成`);
          }
        }

        addLog('[DEBUG] ===== 同步完成 =====');
        addLog(`[DEBUG] 总订单数: ${orderIdList.length}`);
        addLog(`[DEBUG] 成功同步: ${syncedCount} 条`);
        addLog(`[DEBUG] 已存在跳过: ${skippedCount} 条`);
        addLog(`[DEBUG] 错误跳过: ${errorCount} 条`);

        result = {
          code: 0,
          message: `成功同步 ${syncedCount} 条新订单（最近7天，跳过 ${skippedCount} 条已存在，${errorCount} 条错误）`,
          syncedCount,
          skippedCount,
          errorCount,
          debugLogs: debugLogs // 返回所有日志给前端
        };

      } catch (e) {
        addLog('[ERROR] 同步订单失败: ' + e.message);
        addLog('[ERROR] 错误堆栈: ' + e.stack);
        result = {
          code: 500,
          message: `同步失败: ${e.message}`,
          debugLogs: debugLogs
        };
      }
      break;
    }
    case 'syncWechatOrdersAsync': {
      // 异步快速同步版本：立即返回，后台处理
      // 这个方法用于前端调用，避免前端超时
      console.log('[ASYNC-SYNC] 启动异步订单同步...');

      // 立即返回，告诉前端同步已启动
      result = {
        code: 0,
        message: '订单同步已启动，后台处理中...',
        isAsync: true
      };

      // 后台异步执行同步（不等待）
      // 使用 setImmediate 或 Promise 让同步在后台进行
      (async () => {
        try {
          console.log('[ASYNC-SYNC] 后台开始处理订单同步...');

          // 调用完整的同步方法
          const syncRes = await uniCloud.callFunction({
            name: 'order-center',
            data: { action: 'syncWechatOrders' }
          });

          console.log('[ASYNC-SYNC] 后台同步完成:', syncRes.result.message);
        } catch (err) {
          console.error('[ASYNC-SYNC] 后台同步失败:', err.message);
        }
      })();

      break;
    }

    case 'linkOldOrders': {
      // 手动关联旧订单（没有UnionID的订单）
      try {
        const { uid } = event;
        const { storeOpenid } = params; // 用户在微信小店的 openid

        if (!storeOpenid) {
          return {
            code: 400,
            message: '请提供微信小店的OpenID'
          };
        }

        addLog(`[LINK] 开始关联旧订单...`);
        addLog(`[LINK] 用户UID: ${uid}`);
        addLog(`[LINK] 小店OpenID: ${storeOpenid}`);

        // 1. 获取用户当前信息
        const userRes = await db.collection('users').doc(uid).get();
        if (userRes.data.length === 0) {
          return {
            code: 404,
            message: '用户不存在'
          };
        }

        const user = userRes.data[0];
        addLog(`[LINK] 用户当前wx_openid: ${JSON.stringify(user.wx_openid)}`);

        // 2. 更新用户记录，添加小店的 openid
        const wechatStoreAppId = 'wx64874b77c972fb53';
        let newWxOpenid = {};

        if (typeof user.wx_openid === 'string') {
          // 如果是字符串，转换为对象
          newWxOpenid = {};
          newWxOpenid[wechatStoreAppId] = storeOpenid;
        } else if (typeof user.wx_openid === 'object' && user.wx_openid !== null) {
          // 如果是对象，添加新字段
          newWxOpenid = { ...user.wx_openid };
          newWxOpenid[wechatStoreAppId] = storeOpenid;
        } else {
          // 如果不存在，创建新对象
          newWxOpenid = {};
          newWxOpenid[wechatStoreAppId] = storeOpenid;
        }

        addLog(`[LINK] 更新wx_openid为: ${JSON.stringify(newWxOpenid)}`);
        await db.collection('users').doc(uid).update({
          wx_openid: newWxOpenid
        });
        addLog(`[LINK] 已为用户添加小店OpenID`);

        // 2. 重新同步订单
        addLog(`[LINK] 开始重新同步订单...`);

        result = {
          code: 0,
          message: '已关联小店OpenID，请重新点击"同步订单"按钮'
        };
      } catch (e) {
        result = {
          code: 500,
          message: '关联失败: ' + e.message
        };
      }
      break;
    }
    case 'checkMyOpenid': {
      // 检查当前登录用户的openid和unionid
      try {
        const { uid } = event;
        const userRes = await db.collection('users').doc(uid).get();

        if (userRes.data.length === 0) {
          return {
            code: 404,
            message: '用户不存在'
          };
        }

        const user = userRes.data[0];

        result = {
          code: 0,
          message: '查询成功',
          data: {
            uid: user._id,
            nickname: user.nickname,
            wx_unionid: user.wx_unionid,
            wx_openid: user.wx_openid,
            dcloud_appid: user.dcloud_appid,
            // 显示所有字段
            allFields: Object.keys(user)
          }
        };
      } catch (e) {
        result = {
          code: 500,
          message: '查询失败: ' + e.message
        };
      }
      break;
    }
    case 'testWechatAPI': {
      // 测试专用：直接调用微信API，不存储数据，只返回API响应
      try {
        console.log('[TEST] ===== 测试微信小店API =====');

        // 获取access_token
        const tokenRes = await uniCloud.callFunction({
          name: 'wx-api-center',
          data: { action: 'getAccessToken' }
        });

        if (tokenRes.result.code !== 0) {
          return {
            code: 500,
            message: 'access_token获取失败',
            error: tokenRes.result.message
          };
        }

        const accessToken = tokenRes.result.accessToken;
        console.log('[TEST] access_token:', accessToken);

        // 查询2025年9月12号的订单
        const startTime = new Date('2025-09-12T00:00:00+08:00');
        const endTime = new Date('2025-09-12T23:59:59+08:00');

        const listUrl = `https://api.weixin.qq.com/channels/ec/order/list/get?access_token=${accessToken}`;

        const requestData = {
          create_time_range: {
            start_time: Math.floor(startTime.getTime() / 1000),
            end_time: Math.floor(endTime.getTime() / 1000)
          },
          page_size: 100
        };

        console.log('[TEST] 请求URL:', listUrl);
        console.log('[TEST] 请求参数:', JSON.stringify(requestData, null, 2));

        const listRes = await uniCloud.httpclient.request(listUrl, {
          method: 'POST',
          contentType: 'json',
          dataType: 'json',
          data: requestData
        });

        console.log('[TEST] API响应:', JSON.stringify(listRes.data, null, 2));

        // 直接返回API响应，不做任何处理
        result = {
          code: 0,
          message: '微信API测试完成',
          data: {
            api_response: listRes.data,
            request_params: requestData,
            access_token_preview: accessToken ? accessToken.substring(0, 20) + '...' : 'null'
          }
        };
      } catch (e) {
        console.error('[TEST] 测试失败:', e);
        result = {
          code: 500,
          message: '测试失败: ' + e.message,
          error: e.stack
        };
      }
      break;
    }
    case 'getOrders': {
      const { type, page = 1, pageSize = 20 } = params || {};
      const { uid } = event;
      let query = {};
      if (type === 'buyer') {
          query = { buyer_id: uid };
      } else if (type === 'promoter') {
          query = { promoter_id: uid };
      } else {
          // 如果没有指定类型，默认查询购买订单
          query = { buyer_id: uid };
      }

      // 添加分页和限制，避免资源耗尽
      const skip = (page - 1) * pageSize;
      const ordersRes = await db.collection('orders')
        .where(query)
        .orderBy('create_time', 'desc')
        .skip(skip)
        .limit(pageSize)
        .get();

      // 获取总数
      const countRes = await db.collection('orders')
        .where(query)
        .count();

      result = {
        code: 0,
        data: ordersRes.data,
        total: countRes.total,
        page,
        pageSize
      };
      break;
    }

    case 'refreshUserOrders': {
      // 刷新当前用户的订单状态
      const { uid } = event;
      console.log(`[刷新订单] 开始刷新用户 ${uid} 的订单状态...`);

      try {
        // 获取access_token
        const tokenRes = await uniCloud.callFunction({
          name: 'wx-api-center',
          data: { action: 'getAccessToken' }
        });

        if (tokenRes.result.code !== 0) {
          throw new Error(tokenRes.result.message);
        }

        const accessToken = tokenRes.result.accessToken;

        // 查询用户的所有未完成订单（待发货、待收货、已完成但在倒计时期间）
        const dbCmd = db.command;
        const userOrders = await db.collection('orders').where(dbCmd.or([
          { buyer_id: uid, status: dbCmd.in(['unpaid', 'paid', 'shipped']) },
          { promoter_id: uid, status: dbCmd.in(['unpaid', 'paid', 'shipped']) },
          { buyer_id: uid, status: 'completed', activation_countdown: dbCmd.gt(0) },
          { promoter_id: uid, status: 'completed', activation_countdown: dbCmd.gt(0) }
        ])).get();

        console.log(`[刷新订单] 找到 ${userOrders.data.length} 条需要检查的订单`);

        if (userOrders.data.length === 0) {
          result = {
            code: 0,
            message: '没有需要刷新的订单',
            data: { totalCount: 0, updatedCount: 0 }
          };
          break;
        }

        let updatedCount = 0;
        const now = Date.now();

        // 获取系统配置
        const settingsRes = await db.collection('settings').where({ key: 'default' }).get();
        const rules = settingsRes.data[0]?.rules || {};

        for (const order of userOrders.data) {
          try {
            // 调用微信API获取订单最新状态
            const detailUrl = `https://api.weixin.qq.com/channels/ec/order/get?access_token=${accessToken}`;
            const detailRes = await uniCloud.httpclient.request(detailUrl, {
              method: 'POST',
              contentType: 'json',
              dataType: 'json',
              data: { order_id: order._id }
            });

            if (!detailRes.data || detailRes.data.errcode !== 0) {
              console.error(`[刷新订单] 获取订单 ${order._id} 详情失败:`, detailRes.data?.errmsg);
              continue;
            }

            const wechatOrder = detailRes.data.order;
            const wechatStatus = wechatOrder.status;

            // 映射订单状态
            let newStatus = order.status;
            if (wechatStatus === 100) {
              newStatus = 'completed';
            } else if (wechatStatus === 200) {
              newStatus = 'cancelled';
            } else if (wechatStatus === 250) {
              newStatus = 'refunded';
            } else if (wechatStatus === 30) {
              newStatus = 'shipped';
            } else if (wechatStatus === 20) {
              newStatus = 'paid';
            } else if (wechatStatus === 10) {
              newStatus = 'unpaid';
            }

            // 如果状态有变化，更新订单并处理业务逻辑
            if (newStatus !== order.status) {
              console.log(`[刷新订单] 订单 ${order._id} 状态变化: ${order.status} → ${newStatus}`);

              // 更新订单状态
              const updateData = {
                status: newStatus,
                last_sync_time: now
              };

              if (newStatus === 'completed' && !order.completed_time) {
                updateData.completed_time = now;
                updateData.activation_date = now + 7 * 24 * 60 * 60 * 1000;
                updateData.activation_countdown = 7;
              }

              await db.collection('orders').doc(order._id).update(updateData);

              // 处理状态变化的业务逻辑
              const addLog = (msg) => console.log(msg);
              await handleOrderStatusChange(
                order._id,
                order.status,
                newStatus,
                order,
                order.promoter_id,
                order.buyer_id,
                rules,
                addLog
              );

              updatedCount++;
            }

          } catch (err) {
            console.error(`[刷新订单] 处理订单 ${order._id} 失败:`, err.message);
          }
        }

        console.log(`[刷新订单] 完成，共更新 ${updatedCount} 条订单`);

        result = {
          code: 0,
          message: '订单状态刷新完成',
          data: {
            totalCount: userOrders.data.length,
            updatedCount: updatedCount
          }
        };

      } catch (err) {
        console.error('[刷新订单] 失败:', err);
        result = {
          code: 500,
          message: err.message || '刷新订单失败'
        };
      }
      break;
    }

    // ... other cases from original file can be added here if needed ...
    default:
      result = {
        code: 400,
        message: '未知操作'
      };
  }

  return result;
};
